<?php

namespace App\Store\Controllers\Order;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsLog;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Member\SiteMemberLv;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderDeposit;
use App\Store\Models\Order\OrderMaintenance;
use App\Store\Models\Order\OrderRecharge;
use App\Store\Models\Order\OrderSales;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use App\Store\Models\Order\OrderSalesRedflush;
use App\Store\Models\Order\OrderSalesSendGoods;
use App\Store\Models\Wxapp\WxappCouponCodeList;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\Goods;
use Illuminate\Support\Facades\DB;
use App\Common\Services\Common;
use App\Common\Services\Date\TimerRange;
use App\Store\Models\Order\OrderRecovery;
use App\Store\Models\Order\OrderRecoveryGoods;

/**
 * 销售订单详情相关列表
 */
class OrderSalesInfoController extends Controller
{

    /**
     * 订单明细列表
     */
    public function getordergoodslist(Request $request)
    {
        $list = OrderSalesGoods::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 换货明细
     */
    public function getorderchangegoodslist(Request $request)
    {
        $list = OrderSalesRecoveryGoods::getList($request);

        foreach($list['list'] as &$val){
            $val['goodsinfo'] = GoodsStockList::with(['goods_pricetype','goods_brand'])->where(['cp_id' => $val['cp_id'], 'goods_sn_code' => $val['goods_sn_code'],'is_del'=>1])->first();
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    public function getsalesorderlist(Request $request){

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        $where = [];
        $where[]=['cp_id', $cp_id];
        $where[]=['audit_status', '<',3];
        $where[]=['is_del', '=',1];

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if($store_ids){//权限控制

            $where[]=[function ($query) use($store_ids){
                if(is_array($store_ids)){//获取当前权限下的门店
                    return $query->whereIn('store_id',$store_ids);
                }
                if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                    return $query->where('store_id', intval($store_ids));
                }
            }];
        }

        $store_id = intval($request->store_id);
        if ($store_id > 0) {
            $where[] = ['store_id', $store_id];
        }



        $order_at_start = strtotime($request->order_at_start);
        $order_at_end = strtotime($request->order_at_end);
        if ($order_at_start > 0 && $order_at_end > $order_at_start) {
            $where[] = ['order_at', '>=', $order_at_start];
            $where[] = ['order_at', '<=', $order_at_end];
        }


        $timerangetype=intval($request->timerangetype);//今日、本周、本月
        if(in_array($timerangetype,[1,2,3])){
            if($timerangetype==1){
                $time_res=TimerRange::getToday();
                $where[]=[function ($query) use($time_res){
                    return $query->whereBetween('create_at',[$time_res['start_time'],$time_res['end_time']]);
                }];
            }

            if($timerangetype==2){
                $time_res=TimerRange::getThisWeek();
                $where[]=[function ($query) use($time_res){
                    return $query->whereBetween('create_at',[$time_res['start_time'],$time_res['end_time']]);
                }];
            }

            if($timerangetype==3){
                $time_res=TimerRange::getThisMonth();
                $where[]=[function ($query) use($time_res){
                    return $query->whereBetween('create_at',[$time_res['start_time'],$time_res['end_time']]);
                }];
            }
        }



        $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $where[]=[function ($query) use($start_time,$end_time){
                return $query->whereBetween('create_at',[$start_time,$end_time]);
            }];
        }

        $shopping_account_id1 = intval($request->shopping_account_id1);
        if ($shopping_account_id1 > 0) {
            $where[] = ['shopping_account_id1', $shopping_account_id1];
        }
        $shopping_account_id2 = intval($request->shopping_account_id2);
        if ($shopping_account_id2 > 0) {
            $where[] = ['shopping_account_id2', $shopping_account_id2];
        }

        $classesset_id = intval($request->classesset_id);
        if ($classesset_id > 0) {
            $where[] = ['classesset_id', $classesset_id];
        }


        $goods_sn_code = $request->goods_sn_code;

        if ($goods_sn_code != '') {
            $where[] = ['goods_sn_code', $goods_sn_code];
        }

        $ids = $request->ids?? [];
        if (!empty($ids)) {
            $where[] = ['id','in', $ids];
        }

        $goods_sn_code_list=$request->goods_sn_code_list;
        $goods_sn_code_list=$goods_sn_code_list?(is_array($goods_sn_code_list)?$goods_sn_code_list:(explode(',',$goods_sn_code_list))):[];
        if(count($goods_sn_code_list)>0){
            $where[]=[function ($query) use($goods_sn_code_list){
                return $query->whereIn('goods_sn_code',$goods_sn_code_list);
            }];

        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }


        if ($accountinfo['type'] == 11) {
            $sales_where = $where + [
                    ['total_money', '>', $training['training_min']],
                    ['total_money', '<', $training['training_max']],
                ];
        } else {
            $sales_where = $where;
        }


        if ($accountinfo['type'] == 11) {
            $recovery_where = $where + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $recovery_where = $where;
        }

        $list1 = OrderSalesGoods::where($sales_where)->select(['id', DB::raw("1 as type"), 'order_at']);
       // $list1 = OrderSalesGoods::where($sales_where)->select(['id', DB::raw('"1" as type'), 'order_at']);


        $list2 = OrderRecoveryGoods::where($recovery_where)->select(['id',DB::raw("2 as type"), 'order_at']);

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id > 0) {
            $list1->where('goods_category_id',$goods_category_id);
        }

        $goods_category_id_recovery = intval($request->goods_category_id_recovery);
        if ($goods_category_id_recovery > 0) {
            $list1->where('goods_category_id',$goods_category_id_recovery);
        }


        $weight_min = $request->weight_min; $weight_max = $request->weight_max;
        if ($weight_min>0 && $weight_max>$weight_min) {
            $list1->where('weight','>=',$weight_min)->where('weight','<=',$weight_max);
        }

        $recovery_type = intval($request->recovery_type);
        if ($recovery_type > 0) {
            $list2->where('recovery_type',$recovery_type);
        }

        $goods_name = $request->goods_name;
        if ($goods_name != '') {
            $list1->where('goods_name', 'like', '%' . $goods_name . '%');
        }

        $mobile = $request->mobile;
        if ($mobile != '') {
            $ids=Member::where('mobile', 'like', '%' . $mobile . '%')->pluck('id');
            $list1->whereIn('mem_id',$ids);
            $list2->whereIn('mem_id',$ids);
        }


        $order_sn = $request->order_sn;
        if ($order_sn != '') {
            $ids = OrderSales::where('order_sn', 'like', '%' . $order_sn . '%')->pluck('id');
            $ids_r = OrderRecovery::where('order_sn', 'like', '%' . $order_sn . '%')->pluck('id');
            $list1->whereIn('pid', $ids);
            $list2->whereIn('pid', $ids_r);
        }

        $order_type= intval($request->order_type)?? 0;

        if($order_type>0){
            $order_type=$order_type==1?1:2;
            if($order_type==1){
                $list =$list1->orderBy('order_at', 'desc');
            }else{
                $list =$list2->orderBy('order_at', 'desc');
            }
           // $list = ($list1->union($list2))->where(['type'=>$order_type])->orderBy('order_at', 'desc');
        }else{
            $list = ($list1->union($list2))->orderBy('order_at', 'desc');
        }


        $isgetall = intval($request->isgetall) ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $list->paginate($limit)->toArray();
            $list = Common::paginateDataToArray($list);
        } else {
            $list = $list->get()->toArray();
            $list = ['list' => $list];
        }


        foreach ($list['list'] as &$val) {
            if ($val['type'] == 1) {
                $subinfo = OrderSalesGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'classessetinfo'])
                    ->where(['id' => $val['id']])->first();
                $val['subinfo'] =empty($subinfo)? []:$subinfo->toArray();

                $weight =$val['subinfo']['weight']??0;
                $cost_price_discount =$val['subinfo']['cost_price_discount']??0;
                $count =$val['subinfo']['count']??0;

                $goodsinfo = empty($val['subinfo']['goodsinfo']) ? [] : json_decode($val['subinfo']['goodsinfo'], true);
//                //商品工费单件=商品的克销工费+商品的件销工费
//                //商品工费 =克销工费*重量+件销工费*数量
//                $val['goods_costs_price'] = (float)bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0);
//                $val['goods_costs_price_total'] = (float)bcadd(($goodsinfo['gramprice_fee'] ?? 0) * $weight, ($goodsinfo['pieceprice_fee'] ?? 0) * $count, 2);
//
//                //销售工费单件=商品的克销工费+商品的件销工费-工费优惠填的值
//                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
//                $val['sale_costs_price'] = bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0) - $cost_price_discount;
//                $val['sale_costs_price_total'] = $val['goods_costs_price_total'] - ($cost_price_discount * $weight);

//               2025-10-16 再次修改公式调整
                //商品工费单价（字段应该是：商品克销工费）=商品的克销工费
                //商品工费 =克销工费*重量+件销工费
                $val['goods_costs_price'] = (float)($goodsinfo['gramprice_fee'] ?? 0);
                $val['goods_costs_price_total'] = (float)bcadd(($goodsinfo['gramprice_fee'] ?? 0) * $weight, ($goodsinfo['pieceprice_fee'] ?? 0) , 2);

                //销售工费单价（字段应该是：销售克销工费）=商品的克销工费-工费优惠填的值
                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
                $val['sale_costs_price'] = ($goodsinfo['gramprice_fee'] ?? 0) - $cost_price_discount;
                $val['sale_costs_price_total'] = $val['goods_costs_price_total'] - ($cost_price_discount * $weight);


            } elseif ($val['type'] == 2) {
                $val['subinfo'] = OrderRecoveryGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'goods_category', 'classessetinfo'])
                    ->where(['id' => $val['id']])->first()->toArray();
                $val['goods_costs_price']=0;
                $val['goods_costs_price_total']=0;

                $val['sale_costs_price']=0;
                $val['sale_costs_price_total']=0;
            }





        }
        if ($request->isdoexport == 1) {
            return $this->doexportsalesorder($list['list'],$request);
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function doexportsalesorder($list,$request)
    {

        $exceldata = [];
        $row = [
            ['table_header'=>'销售订单明细'],
            [
                'order_sn' => '订单号',
                'type'=>'订单类型',
                'store_name' => '所属门店',
                'order_at'=>'下单时间',
                'shopping_account_info1' => '导购',
                'goods_sn_code' => '条码',
                'goods_name' => '商品名称',
                'goods_category_name' => '商品类别',
                'goods_category_name_recovery'=>'旧料品类',
                'change_type'=>'换货方式',
                'recovery_type'=>'回收方式',
                'goods_style_name' => '款式',
                'count'=>'数量',
                'label_price'=>'标签价',
                'discount'=>'折扣',
                'total_money'=>'应收金额',
                'weight_old'=>'货重',
                'weight'=>'销售重量',
                'price'=>'销售单价',
                'goods_costs_price' => '商品工费单价',
                'goods_costs_price_total' => '商品工费',
                'sale_costs_price' => '销售工费单价',
                'sale_costs_price_total' => '销售工费',
                'real_total_money'=>'实收金额',

                'weight_recovery'=>'回收重量',
                'price_recovery'=>'回收金价',
                'd_price_recovery'=>'回收标价',
                'loss_weight_recovery'=>'损耗重量',
                'money_recovery'=>'回收金额',

                'performance'=>'业绩金额',
                'order_points'=>'获得积分',
                'commission1_total'=>'提成',
                'sales_price' => '牌价',
                'old_recovery_price' => '料价',

                'brand_name'=>'品牌',
                'goods_pricetype_name'=>'价格类型',
                'cf_no'=>'证书号',
                'color'=>'颜色',
                'clarity'=>'净度',
                'is_change'=>'是否已换',
                'mobile'=>'会员电话',
                'real_name'=>'会员姓名',
                'remark'=>'备注',
            ]
        ];

        foreach($list as $val){

            if($val['type']==1){
                $info=$val['subinfo'];

                $goods_info=json_decode($info['goodsinfo'],true);
                $subinfo = OrderSalesGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'classessetinfo'])
                    ->where(['id' => $val['id']])->first();
                $val['subinfo'] =empty($subinfo)? []:$subinfo->toArray();

                $weight =$val['subinfo']['weight']??0;
                $cost_price_discount =$val['subinfo']['cost_price_discount']??0;
                $count =$val['subinfo']['count']??0;

                $goodsinfo = empty($val['subinfo']['goodsinfo']) ? [] : json_decode($val['subinfo']['goodsinfo'], true);
//                //商品工费单件=商品的克销工费+商品的件销工费
//                //商品工费 =克销工费*重量+件销工费*数量
//                $val['goods_costs_price'] = (float)bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0);
//                $val['goods_costs_price_total'] = (float)bcadd(($goodsinfo['gramprice_fee'] ?? 0) * $weight, ($goodsinfo['pieceprice_fee'] ?? 0) * $count, 2);
//
//                //销售工费单件=商品的克销工费+商品的件销工费-工费优惠填的值
//                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
//                $val['sale_costs_price'] = bcadd($goodsinfo['gramprice_fee'] ?? 0, $goodsinfo['pieceprice_fee'] ?? 0) - $cost_price_discount;
//                $val['sale_costs_price_total'] = $val['goods_costs_price_total'] - ($cost_price_discount * $weight);

//               2025-10-16 再次修改公式调整
                //商品工费单价（字段应该是：商品克销工费）=商品的克销工费
                //商品工费 =克销工费*重量+件销工费
                $val['goods_costs_price'] = (float)($goodsinfo['gramprice_fee'] ?? 0);
                $val['goods_costs_price_total'] = (float)bcadd(($goodsinfo['gramprice_fee'] ?? 0) * $weight, ($goodsinfo['pieceprice_fee'] ?? 0) , 2);

                //销售工费单价（字段应该是：销售克销工费）=商品的克销工费-工费优惠填的值
                //销售工费=商品工费-工费优惠（开单页面填的那个值）*重量
                $val['sale_costs_price'] = ($goodsinfo['gramprice_fee'] ?? 0) - $cost_price_discount;
                $val['sale_costs_price_total'] = $val['goods_costs_price_total'] - ($cost_price_discount * $weight);

                $exceldata[] = [
                    'order_sn' => $info['orderinfo']['order_sn'],
                    'type'=>'销售开单',
                    'store_name' => $info['storeinfo']['store_name'],
                    'order_at'=>date('Y-m-d',$info['orderinfo']['order_at']),
                    'shopping_account_info1' => $info['shoppingaccountinfo1']['real_name'],
                    'goods_sn_code' => $goods_info['goods_sn_code'],
                    'goods_name' => $info['goods_name'],
                    'goods_category_name' => $goods_info['goods_category']['category_name'],
                    'goods_category_name_recovery'=>'',
                    'change_type'=>'',
                    'recovery_type'=>'',
                    'goods_style_name' =>  isset( $goods_info['goods_style']['style_name'])? $goods_info['goods_style']['style_name']:'',
                    'count'=>$info['count'],
                    'label_price'=>$info['label_price']/100,
                    'discount'=>$info['discount'],
                    'total_money'=>$info['total_money']/100,
                    'weight_old'=>$info['weight_old'],
                    'weight'=>$info['weight'],
                    'price'=>$info['price']/100,

                    'goods_costs_price' => $val['goods_costs_price']/100,
                    'goods_costs_price_total' => $val['goods_costs_price_total']/100,
                    'sale_costs_price' =>  $val['sale_costs_price']/100,
                    'sale_costs_price_total' => $val['sale_costs_price_total']/100,
                    //'cost_price' => $info['cost_price']/100,
                    //'cost_price_real' => (($info['cost_price']-$info['cost_price_discount'])*$info['weight']) /100,
                    //cost_price_total' => ((($info['cost_price']-$info['cost_price_discount'])*$info['weight'])+($info['pieceprice_fee']*$info['count']))/100,
                    'real_total_money'=>$info['real_total_money']/100,

                    'weight_recovery'=>'',
                    'price_recovery'=>'',
                    'd_price_recovery'=>'',
                    'loss_weight_recovery'=>'',
                    'money_recovery'=>'',

                    'performance'=>$info['performance']/100,
                    'order_points'=>$info['order_points'],
                    'commission1_total'=>$info['commission1_total']/100,
                    'sales_price' => $info['sales_price']/100,
                    'old_recovery_price' => $info['old_recovery_price']/100,
                    'brand_name'=>isset( $goods_info['goods_brand']['brand_name'])? $goods_info['goods_brand']['brand_name']:'',
                    'goods_pricetype_name'=>isset( $goods_info['goods_pricetype']['goods_pricetype_name'])? $goods_info['goods_pricetype']['goods_pricetype_name']:'',
                    'cf_no'=>$goods_info['cf_no'],
                    'color'=>$goods_info['color'],
                    'clarity'=>$goods_info['clarity'],
                    'is_change'=>$info['is_exchange']==2?'是':'否',
                    'mobile' => $info['memberinfo']?$info['memberinfo']['mobile']:'',
                    'real_name' => $info['memberinfo']?$info['memberinfo']['real_name']:'',
                    'remark' => $info['orderinfo']['remark'],

                ];
            }else{
                $info=$val['subinfo'];

                $exceldata[] = [
                    'order_sn' => $info['orderinfo']['order_sn'],
                    'type'=>'纯回收',
                    'store_name' => $info['storeinfo']['store_name'],
                    'order_at'=>date('Y-m-d',$info['orderinfo']['order_at']),
                    'shopping_account_info1' => $info['shoppingaccountinfo1']['real_name'],

                    'goods_sn_code' => $info['goods_sn_code'],
                    'goods_name' => '',
                    'goods_category_name' => '',
                    'goods_category_name_recovery'=>$info['goods_category']['category_name'],
                    'change_type'=>$info['change_type']==1?'回收':'上柜',
                    'recovery_type'=>$info['recovery_type']==1?'按克':'标价',
                    'goods_style_name' => '',
                    'count'=>$info['count'],
                    'label_price'=>'',
                    'discount'=>'',
                    'total_money'=>'',
                    'weight_old'=>'',
                    'weight'=>'',
                    'price'=>'',
                    'goods_costs_price' => '',
                    'goods_costs_price_total' => '',
                    'sale_costs_price' =>  '',
                    'sale_costs_price_total' => '',
                   // 'cost_price' => '',
                    //'cost_price_real' => '',
                    //'cost_price_total' => '',
                    'real_total_money'=>'',

                    'weight_recovery'=>$info['weight'],
                    'price_recovery'=>$info['price']/100,
                    'd_price_recovery'=>$info['d_price']/100,
                    'loss_weight_recovery'=>$info['loss_weight'],
                    'money_recovery'=>$info['money']/100,
                    'performance'=>$info['performance']/100,
                    'order_points'=>'',
                    'commission1_total'=>$info['commission1']/100,

                    'sales_price' => '',
                    'old_recovery_price' => '',
                    'brand_name'=>'',
                    'goods_pricetype_name'=>'',
                    'cf_no'=>'',
                    'color'=>'',
                    'clarity'=>'',
                    'is_change'=>'',
                    'mobile' => $info['memberinfo']?$info['memberinfo']['mobile']:'',
                    'real_name' => $info['memberinfo']?$info['memberinfo']['real_name']:'',
                    'remark' => $info['orderinfo']['remark'],
                ];
            }

        }

        $filename = '订单明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }


    public function getotherorderinfo(Request $request)
    {


        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        // if($store_ids){//权限控制
        //     if(is_array($store_ids)){//获取当前权限下的门店
        //         $query->whereIn('store_id',$store_ids);
        //     }
        //     if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
        //         $query->where('store_id', intval($store_ids));
        //     }
        // }


        $where = [];
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $where[]=['cp_id', $cp_id];
        $where[]=['audit_status', '<',3];
        $store_id = intval($request->store_id);//门店
        if ($store_id>0) {
            $where[] = ['store_id', $store_id];
        }

        $order_at_start = strtotime($request->order_at_start);
        $order_at_end = strtotime($request->order_at_end);
        if ($order_at_start > 0 && $order_at_end > $order_at_start) {
            $where[] = ['order_at', '>=', $order_at_start];
            $where[] = ['order_at', '<=', $order_at_end];
        }

        $shopping_account_id1 = intval($request->shopping_account_id1);
        if ($shopping_account_id1 > 0) {
            $where[] = ['shopping_account_id1', $shopping_account_id1];
        }
        $shopping_account_id2 = intval($request->shopping_account_id2);
        if ($shopping_account_id2 > 0) {
            $where[] = ['shopping_account_id2', $shopping_account_id2];
        }
        $classesset_id = intval($request->classesset_id);
        if ($classesset_id > 0) {
            $where[] = ['classesset_id', $classesset_id];
        }

        $pay_type_id = intval($request->pay_type_id);
        if ($pay_type_id > 0) {
            $where[] = ['pay_type_id', $pay_type_id];
        }

        $audit_status = intval($request->audit_status);
        if ($audit_status>0) {
            $where[] = ['audit_status', $audit_status];
        }

        $timerangetype=intval($request->timerangetype);//今日、本周、本月
        if(in_array($timerangetype,[1,2,3])){
            if($timerangetype==1){
                $time_res=TimerRange::getToday();
                $where[]=[function ($query) use($time_res){
                    return $query->whereBetween('create_at',[$time_res['start_time'],$time_res['end_time']]);
                }];
            }

            if($timerangetype==2){
                $time_res=TimerRange::getThisWeek();
                $where[]=[function ($query) use($time_res){
                    return $query->whereBetween('create_at',[$time_res['start_time'],$time_res['end_time']]);
                }];
            }

            if($timerangetype==3){
                $time_res=TimerRange::getThisMonth();
                $where[]=[function ($query) use($time_res){
                    return $query->whereBetween('create_at',[$time_res['start_time'],$time_res['end_time']]);
                }];
            }
        }

        $order_sn = $request->order_sn;

        if ($order_sn!='') {
            $where[] = ['order_sn', 'like','%'.$order_sn.'%'];
        }
        $real_name = $request->real_name;
        $ids_realname=false;
        $ids_mobile=false;
        $ids_mem_card_no=false;
        $ids_all=false;
        if ($real_name != '') {
            $ids_realname=Member::where('real_name', 'like', '%' . $real_name . '%')->where('is_del',1)->pluck('id')->toArray();
        }

        $mobile = $request->mobile;
        if ($mobile != '') {
            $ids_mobile=Member::where('mobile', 'like', '%' . $mobile . '%')->pluck('id')->toArray();
        }

        $mem_card_no = $request->mem_card_no;
        if ($mem_card_no != '') {
            $ids_mem_card_no=Member::where('mem_card_no', 'like', '%' . $mem_card_no . '%')->pluck('id')->toArray();
        }
        if($ids_realname!==false || $ids_mobile!==false || $ids_mem_card_no!==false){
            $ids_realname=$ids_realname?$ids_realname:[];
            $ids_mobile=$ids_mobile?$ids_mobile:[];
            $ids_mem_card_no=$ids_mem_card_no?$ids_mem_card_no:[];
            $ids_all=array_unique(array_merge($ids_realname,$ids_mobile,$ids_mem_card_no));
        }

        $list1 = OrderDeposit::where($where)->where(function ($q) use($store_ids,$ids_all){
            if(is_array($store_ids)){//获取当前权限下的门店
                $q->whereIn('store_id',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $q->where('store_id', intval($store_ids));
            }
            if($ids_all!==false){
                $q->whereIn('member_id',$ids_all);
            }

        })->select(['id', DB::raw('"1" as type'), 'order_at']);

        $list2 = OrderMaintenance::where($where)->where(function ($q) use($store_ids,$ids_all){
            if(is_array($store_ids)){//获取当前权限下的门店
                $q->whereIn('store_id',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $q->where('store_id', intval($store_ids));
            }
            if($ids_all!==false){
                $q->whereIn('member_id',$ids_all);
            }

        })->select(['id', DB::raw('"2" as type'), 'order_at']);

        $list3 = OrderRecharge::where($where)->where(function ($q) use($store_ids,$ids_all){
            if(is_array($store_ids)){//获取当前权限下的门店
                $q->whereIn('store_id',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $q->where('store_id', intval($store_ids));
            }
            if($ids_all!==false){
                $q->whereIn('member_id',$ids_all);
            }

        })->select(['id', DB::raw('"3" as type'), 'order_at']);



        $order_type= intval($request->order_type);

        if($order_type>0){
            echo $order_type;
            $order_type=$order_type==1?1:2;
            $list = ($list1->union($list2)->union($list3))
                ->where('type', $order_type)  // 在临时表上筛选
                ->orderBy('order_at', 'desc')
                ->get();
        }else{
            $list = $list1->union($list2)->union($list3)->orderBy('order_at', 'desc');
        }

        $isgetall = intval($request->isgetall) ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $list->paginate($limit)->toArray();
            $list = Common::paginateDataToArray($list);
        } else {
            $list = $list->get()->toArray();
            $list = ['list' => $list];
        }

        foreach ($list['list'] as &$val) {
            if ($val['type'] == 1) {
                $val['subinfo'] = OrderDeposit::with(['memberinfo', 'storeinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2'])
                    ->where(['id' => $val['id']])->first()->toArray();
            } elseif ($val['type'] == 2) {
                $val['subinfo'] = OrderMaintenance::with(['memberinfo', 'storeinfo',  'shoppingaccountinfo1', 'shoppingaccountinfo2'])
                    ->where(['id' => $val['id']])->first()->toArray();
            } elseif ($val['type'] == 3) {
                $val['subinfo'] = OrderRecharge::with(['memberinfo', 'storeinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2'])
                    ->where(['id' => $val['id']])->first()->toArray();
            }
        }

        if ($request->isdoexport == 1) {
            return $this->doexportotherorder($list['list'],$request);
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function doexportotherorder($list,$request)
    {
        $exceldata = [];
        //会员姓名、会员电话、订单号、定金金额、商品图片、充值金额、赠送金额、赠送积分、维修内容、维修金额、下单时间、备注
        $row = [
            ['table_header'=>'其他订单明细'],
            [
                'type' => '订单类型',
                'mobile'=>'会员电话',
                'real_name'=>'会员姓名',
                'order_sn' => '订单号',
                'money1' => '定金金额',
                'money3' => '充值金额',
                'send_money' => '赠送金额',
                'send_points' => '赠送积分',
                // 'send_points' => '维修内容',
                'money2' => '维修金额',
                'order_at'=>'下单时间',
                // 'shopping_account_info1' => '导购',
                'remark' => '备注',
            ]
        ];

        foreach($list as $vval){
            $exceldata[] = [
                'type' => $vval['type']==1?'定金开单' : ($vval['type']==2?'维修开单':'充值开单'),
                'mobile' => isset($vval['subinfo']['memberinfo']) ? $vval['subinfo']['memberinfo']['mobile'] : '',
                'real_name' =>  isset($vval['subinfo']['memberinfo']) ? $vval['subinfo']['memberinfo']['real_name'] : '',
                'order_sn' => $vval['subinfo']['order_sn'],
                'money1' => $vval['type']==1?$vval['subinfo']['money']/100:'',
                'money3' => $vval['type']==3?$vval['subinfo']['money']/100:'',
                'send_money' => $vval['type']==3?$vval['subinfo']['send_money']/100:'',
                'send_points' => $vval['type']==3?$vval['subinfo']['send_points']:'',
                'money2' => $vval['type']==2?$vval['subinfo']['money']/100:'',
                'order_at'=>date('Y-m-d',$vval['subinfo']['order_at']),
                //'shopping_account_info1' => isset($vval['subinfo']['shoppingaccountinfo1']) ? $vval['subinfo']['shoppingaccountinfo1']['real_name'] : '',
                'remark'=>$vval['subinfo']['remark'],
            ];
        }

        $filename = '其他订单明细导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 导出订单明细列表
     */
    public function exportordergoodslist(Request $request)
    {
        $list = OrderSalesGoods::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['table_header'=>'订单明细'],
            [
                'order_sn' => '订单号',
                'order_at'=>'下单时间',
                'shopping_account_info1' => '导购',
                'goods_sn_code' => '条码',
                'goods_name' => '商品名称',
                'goods_category_name' => '商品类别',
                'goods_style_name' => '款式',
                'count'=>'数量',
                'label_price_old'=>'原标价',
                'label_price'=>'标价',
                'discount'=>'折扣',
                'total_money'=>'应收金额',
                'weight_old'=>'货重',
                'weight'=>'销售重量',
                'price'=>'销售单价',
                'cost_price' => '商品工费单价',
                'cost_price_real' => '销售工费单价',
                'cost_price_total' => '销售工费',
                'real_total_money'=>'实收金额',
                'performance'=>'业绩金额',
                'order_points'=>'获得积分',
                'commission1_total'=>'提成',
                'sales_price' => '牌价',
                'old_recovery_price' => '料价',

                'brand_name'=>'品牌',
                'goods_pricetype_name'=>'价格类型',
                'goods_craft_name'=>'工艺',
                'cf_no'=>'证书号',
                'color'=>'颜色',
                'clarity'=>'净度',
                'main_stone_weigth'=>'主石重',
                'main_stone_val'=>'主石值',
                'other_stone_weigth'=>'副石重',
                'other_stone_count'=>'副石数',
                'other_stone_val'=>'副石值',
                'is_change'=>'是否已换',
                'mobile'=>'会员电话',
                'real_name'=>'会员姓名',
            ]
        ];

        foreach($list as $val){
            $goods_info=json_decode($val['goodsinfo'],true);
            $exceldata[] = [
                'order_sn' => $val['orderinfo']['order_sn'],
                'order_at'=>date('Y-m-d',$val['orderinfo']['order_at']),
                'shopping_account_info1' => $val['shoppingaccountinfo1']['real_name'],
                'goods_sn_code' => $goods_info['goods_sn_code'],
                'goods_name' => $val['goods_name'],
                'goods_category_name' => $goods_info['goods_category']['category_name'],
                'goods_style_name' =>  isset( $goods_info['goods_style']['style_name'])? $goods_info['goods_style']['style_name']:'',
                'count'=>$val['count'],
                'label_price_old'=>$val['label_price_old']/100,
                'label_price'=>$val['label_price']/100,
                'discount'=>$val['discount'],
                'total_money'=>$val['total_money']/100,
                'weight_old'=>$val['weight_old'],
                'weight'=>$val['weight'],
                'price'=>$val['price']/100,
                'cost_price' => $val['cost_price']/100,
                'cost_price_real' =>(($val['cost_price']-$val['cost_price_discount'])*$val['weight']) /100,
                'cost_price_total' =>  ((($val['cost_price']-$val['cost_price_discount'])*$val['weight'])+($val['pieceprice_fee']*$val['count']))/100,
                'real_total_money'=>$val['real_total_money']/100,
                'performance'=>$val['performance']/100,
                'order_points'=>$val['order_points'],
                'commission1_total'=>$val['commission1_total']/100,
                'sales_price' => $val['sales_price']/100,
                'old_recovery_price' => $val['old_recovery_price']/100,

                'brand_name'=>isset( $goods_info['goods_brand']['brand_name'])? $goods_info['goods_brand']['brand_name']:'',
                'goods_pricetype_name'=>isset( $goods_info['goods_pricetype']['goods_pricetype_name'])? $goods_info['goods_pricetype']['goods_pricetype_name']:'',
                'goods_craft_name'=>isset( $goods_info['goods_craft']['craft_name'])? $goods_info['goods_craft']['craft_name']:'',
                'cf_no'=>$goods_info['cf_no'],
                'color'=>$goods_info['color'],
                'clarity'=>$goods_info['clarity'],
                'main_stone_weigth'=>$goods_info['main_stone_weigth'],
                'main_stone_val'=>$goods_info['main_stone_val'],
                'other_stone_weigth'=>$goods_info['other_stone_weigth'],
                'other_stone_count'=>$goods_info['other_stone_count'],
                'other_stone_val'=>$goods_info['other_stone_val'],
                'is_change'=>$val['is_exchange']==2?'是':'否',
                'mobile' => $val['memberinfo']?$val['memberinfo']['mobile']:'',
                'real_name' => $val['memberinfo']?$val['memberinfo']['real_name']:'',
            ];
        }

        $filename = '订单明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);



    }

     /**
     * 导出换货明细
     */
    public function exportorderchangegoodslist(Request $request)
    {
        $list = OrderSalesRecoveryGoods::getList($request)['list'];

        $row = [
            ['table_header'=>'换货明细'],
            [
            'order_sn' => '订单号',
            'change_type' => '换货方式',
            'goods_sn_code' => '回收条码',
            'recovery_type' => '回收方式',
            'goods_catefory_name' => '旧料类别',
            'count' => '数量',
            'weight' => '回收重量',
            'real_weight' => '回收重量',
            'price' => '旧料单价',
            'd_price' => '旧料标价',
            'dold_fee' => '工费',
            'sales_price' => '牌价',
            'old_recovery_price' => '料价',
            'recovery_type_price'=>'回收类型',
            'discount' => '换货折扣',
            'money' => '换货金额',
            'money1' => '回收金额',
            'commission1' => '提成',
            'dold_price' => '折旧单价',
            'dold_fee1' => '折旧费',
            'goods_pricetype_name' => '价格类型',
            'cf_no' => '证书号',
            'shopping_account_info1' => '导购',
            'brand_name' => '品牌',
            'remark' => '备注',
            'create_at'=>'操作时间'

        ]];

        $exceldata = [];
        foreach ($list as $val) {
            $goodsinfo = GoodsStockList::with(['goods_pricetype','goods_brand'])->where(['cp_id' => $val['cp_id'], 'goods_sn_code' => $val['goods_sn_code']])->first();
            $exceldata[] = [
                'order_sn' => $val['orderinfo']['order_sn'],
                'change_type' => $val['change_type']==1?'回收':"上柜",
                'goods_sn_code' => $val['goods_sn_code'],
                'recovery_type' => $val['recovery_type']==1?'按克':"标价",
                'goods_catefory_name' => $val['goods_category']['category_name'],
                'count' => $val['count'],
                'weight' => $val['weight'],
                'real_weight'=>$val['weight']-$val['loss_weight'],
                'price' => $val['price'],
                'd_price' => $val['d_price']/100,
                'dold_fee' => $val['dold_fee']/100,

                'sales_price' => $val['sales_price']/100,
                'old_recovery_price' => $val['old_recovery_price']/100,
                'recovery_type_price' => $val['recovery_type_price']==1?'增值回收':($val['recovery_type_price']==2?'牌价回收':'料价回收'),//1增值回收、2牌价回收、3料价回收
                'discount' => $val['discount'],
                'money' => $val['money']/100,
                'money1' => $val['money']/100,
                'commission1' => $val['commission1']/100,
                'dold_price' => $val['dold_price']/100,
                'dold_fee1' => $val['dold_fee']/100,
                'goods_pricetype_name'=>isset( $goodsinfo['goods_pricetype']['goods_pricetype_name'])? $goodsinfo['goods_pricetype']['goods_pricetype_name']:'',
                'cf_no' => $goodsinfo?$goodsinfo['cf_no']:'',
                'shopping_account_info1' => $val['shoppingaccountinfo1']?$val['shoppingaccountinfo1']['real_name']:'',
                'brand_name'=>isset( $goodsinfo['goods_brand']['brand_name'])? $goodsinfo['goods_brand']['brand_name']:'',
                'remark' => $val['remark'],
                'create_at' =>$val['create_at']>0? date('Y-m-d H:i:s',$val['create_at']): '',
            ];
        }

        $filename = '换货明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }


    /**
     *获取列表
     */
    public  function getsalesGoods(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $goods_sn_code = $request->goods_sn_code;
        if (empty($goods_sn_code)) {
            return response()->json(['code' => '201', 'msg' => '商品条码不能为空']);
        }
        $query = OrderSalesGoods::with(['storeinfo', 'orderinfo']);

        $query->where(['cp_id' => $cp_id, 'is_del' => 1,'goods_sn_code'=>$goods_sn_code,'red_status'=>1])
            ->where('audit_status','<>',3)
            ->orderBy('create_at', 'desc');
        $limit = $request->limit ?? 0;
        if ($limit>0) {
            $list = $query->paginate($limit)->toArray();
            $list= Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            $list= ['list' => $list];
        }


        foreach ($list['list']  as &$item){
            $item['order_sn'] =$item['orderinfo']['order_sn']?? '';

        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);




    }





}
